var fs = true;
// 储存临时已扫描的条码
var scannedBarcodes = []; // 每个元素格式: { barcode: "条码编号", materialNo: "物料号", materialName: "物料名称" }

// 储存临时未扫描的物料
var StockList = [];
var UserName = localStorage.getItem("UserName");
var UserNO=localStorage.getItem("UserNO");
var ColorNO=localStorage.getItem("ColorNO");

mui.plusReady(function() {
	var currentwindow = plus.webview.currentWebview();
	if (currentwindow.TradeOrderNO != '' && currentwindow.TradeOrderNO != undefined) {
		$("#TradeOrderNO").val(currentwindow.TradeOrderNO);		
			$("#hPageIndex").val(1);	
		$("#shelfOption").val(ColorNO);
	} else {
		mui.toast("No parameters brought in。", {
			duration: '1000',
			type: 'div'
		});
	}
	mui('.mui-scroll-wrapper').scroll();
	mui('body').on('shown', '.mui-popover', function(e) {
		//console.log('shown', e.detail.id);//detail为当前popover元素
	});
	mui('body').on('hidden', '.mui-popover', function(e) {
		//console.log('hidden', e.detail.id);//detail为当前popover元素
	});
	
	GetCalculateInfo();
	

	//获取未下架的条码
	//GetTradeCodeList();

	BandCode();

	$("#all").html("");
	$("#all").html(
		'<a style="font-size:100px; color:#F27D48; display:block; text-align:center;" class="mui-icon mui-icon-search"></a><a class="mui-title" style="color:#808080; position: initial; margin: 0 auto; height:' +
		(window.screen.height - 380) + 'px">No data available at the moment</a>');
	$("#BarCode").focus();
	plus.nativeUI.closeWaiting();
	//显示当前页面
	//mui.currentWebview.show();
});

// 更新库存列表显示
function UpdateStockListDisplay() {
	$("#all").html(""); // 清空显示
 
	if (StockList.length === 0) {
		$("#all").html(
			'<a style="font-size:100px; color:#F27D48; display:block; text-align:center;" class="mui-icon mui-icon-search"></a><a class="mui-title" style="color:#808080; position: initial; margin: 0 auto; height:' +
			(window.screen.height - 480) + 'px">No data available at the moment</a>');
		return;
	}

	StockList.forEach(item => {
		
		var itemClass = item.RState == "1" ? 'locked-item' : '';

	
		$("#all").append(
			`<li class="mui-table-view-cell ${itemClass}"  onclick="openPosition('${item.BarcodeNO}','${item.StockQty}')">
                <div class="list-title" >Code:${item.BarcodeNO}&nbsp;&nbsp;&nbsp;Qty:${item.StockQty}</div>
			   <div class="list-detail">Part:${item.MaterialNO}&nbsp;&nbsp;&nbsp;LOT:${item.BatchNO}</div>
                <div class="list-detail">Lamp:${item.LampNO}&nbsp;&nbsp;&nbsp;Storage:${item.StorageNO}</div>
            </li>`
		);
        	

	});
}

//绑定扫码下架
function BandCode() {
	// 绑定 MaterialCode 输入框的 keyup 事件
	$("#BarCode").keyup(function(event) {
		event.preventDefault();
		// 检查是否按下了回车键（keyCode 13）
		if (event.keyCode == 13) {

			var BarCode = $("#BarCode").val();
			// 检查 BarCode 是否为空
			if (!BarCode) {
				mui.toast("Please scan the BarCode。", {
					duration: '1000',
					type: 'div'
				});
				$("#BarCode").focus();
				return;
			}
			if (BarCode.indexOf("||") !== -1) { // 或者用 includes("||")
				BarCode = BarCode.split("||")[0];
				//console.log("解析到的条码:", firstBarcode); 
			}
			$("#BarCode").val(BarCode);
			// 检查条码是否在StockList中
			var index = StockList.findIndex(item => item.BarcodeNO === BarCode);
			if (index === -1) {
				mui.toast("Barcode not found in current stock list", {
					duration: '1000',
					type: 'div'
				});
				Audios();
				$("#BarCode").val('');
				$("#BarCode").focus();
				return;
			}

			var datas = {
				Color: 0,
				TradeType:3,
				LigthCheck: false,
				OrderNO: $("#TradeOrderNO").val(),
				Items: [{
					BarcodeNO: BarCode
				}]
			};
			var totalStockQty = Number(StockList[index].StockQty);
			var Qty = Number($("#Qty").val());
			// 发送请求
			xccFormPostAsync("api/PDA/AllCodeLigthInfo", datas, function(data) {
				document.activeElement.blur();
				if (data.Code === 200) {
					if ((Qty - totalStockQty) <= 0)
						$("#Qty").val(0);
					else
						$("#Qty").val(Qty - totalStockQty);
					// 从StockList中移除已下架的条码
					
					// 更新显示
					GetCalculateInfo();
					mui.toast("success", {
						duration: '1000',
						type: 'div'
					});
				
					$("#BarCode").val('');
					$("#BarCode").focus();
				}
			}, function(error) {
				Audios();
			});

		}
		$("#BarCode").focus();
	});
}
//全部下架
function AllDown() {
	
	var ColorNO = $("#shelfOption").val();
	var datas = {
		OrderNO: $("#TradeOrderNO").val(),
		Color: ColorNO,
		TradeType:3,
		UserName: UserNO,
		LigthCheck: false,
		Items: StockList
	};
	var totalStockQty = 0;
	var Qty = Number($("#Qty").val());
	xccFormPostAsync("api/PDA/AllCodeLigthInfo", datas, function(data) {
		if (data.Code === 200) {
			mui.toast("success ", {
				duration: '1000',
				type: 'div'
			});

			$("#all").html("");
			$("#all").html(
				'<a style="font-size:100px; color:#F27D48; display:block; text-align:center;" class="mui-icon mui-icon-search"></a><a class="mui-title" style="color:#808080; position: initial; margin: 0 auto; height:' +
				(window.screen.height - 480) + 'px">No data available at the moment</a>');
			totalStockQty = StockList.reduce((sum, item) => sum + item.StockQty, 0);
			if ((Qty - totalStockQty) <= 0)
				$("#Qty").val(0);
			else
				$("#Qty").val(Qty - totalStockQty);
			GetCalculateInfo();
		
		} else {
			mui.toast("error " + data.Message, {
				duration: '1000',
				type: 'div'
			});
			Audio();
		}
	}, function(errr) {
		Audio();
	})
}


function openPosition(BarcodeNO, StockQty) {

	// 显示选择对话框
	showSelectionDialog(BarcodeNO, StockQty);

}

function showSelectionDialog(BarcodeNO, StockQty) {
	// 创建对话框元素
	const dialog = document.createElement('div');
	dialog.className = 'selection-dialog';
	dialog.innerHTML = `
        <p>条码:${BarcodeNO},请选择操作:</p>
        <button class="mui-btn mui-btn-primary" onclick="handleSelection('singleCode','${BarcodeNO}','${StockQty}')">拆包</button>
        <button class="mui-btn mui-btn-danger" onclick="handleSelection('cancel', '${BarcodeNO}', '${StockQty}')">取消</button>
    `;

	// 将对话框添加到 body
	document.body.appendChild(dialog);

	// 添加关闭对话框的事件监听器
	dialog.addEventListener('click', function(event) {
		if (event.target === dialog) {
			dialog.remove();
		}
	});
}

function handleSelection(action, BarcodeNO, StockQty) {
	// 根据选择的操作执行相应的逻辑
	switch (action) {
		case 'cancel':
			console.log('取消操作');
			break;
		case 'singleCode':
			// 打开新窗口并保存返回的Webview对象
			var codeUnpackingWebview = mui.openWindow({
				url: 'WMS_TradeCodeUnpacking.html',
				id: 'WMS_TradeCodeUnpacking', // 添加id以便后续引用
				extras: {
					BarcodeNO: BarcodeNO,
					StockQty: StockQty,
					TradeOrderNO: $("#TradeOrderNO").val()
				},
				createNew: true, // 创建新的webview
				show: {
					autoShow: true, // 页面loaded事件发生后自动显示
					aniShow: 'pop-in' // 显示动画
				},
				waiting: {
					autoShow: true // 自动显示等待框
				}
			});

			// 监听页面关闭事件
			codeUnpackingWebview.addEventListener('close', function() {
				console.log('WMS_CodeUnpacking.html已关闭');
				// 在这里执行你的回调逻辑
				UpdateStockListDisplay() // 例如刷新列表
				// 或者执行其他需要的操作
			});
			break;
	}

	// 移除对话框
	document.querySelector('.selection-dialog').remove();
}


//亮灯
function LigthUP() {
	var ColorNO = $("#shelfOption").val();
	localStorage.setItem("ColorNO",ColorNO);
	
	var datas = {
		Color: ColorNO,
		LigthCheck: true,
		Items: StockList
	};
	xccFormPostAsync("api/PDA/QueryLigthInfo", datas, function(data) {
		if (data.Code === 200) {
			mui.toast("success ", {
				duration: '1000',
				type: 'div'
			});
		} else {
			mui.toast("error " + data.Message, {
				duration: '1000',
				type: 'div'
			});
		}
	}, function(errr) {})
}

//灭灯
function LigthOff() {
	var ColorNO = $("#shelfOption").val();
	var datas = {
		Color: 0,
		LigthCheck: false,
		Items: StockList
	};
	xccFormPostAsync("api/PDA/QueryLigthInfo", datas, function(data) {
		if (data.Code === 200) {
			mui.toast("success ", {
				duration: '1000',
				type: 'div'
			});
		} else {
			mui.toast("error " + data.Message, {
				duration: '1000',
				type: 'div'
			});
		}
	}, function(errr) {})
}

//捡料算料
function GetCalculateInfo() {
	var html = "";
	xccFormPostAsync("api/PDA/TradePickBarcode", {
		TradeOrderNO: $("#TradeOrderNO").val(),
		PageIndex: 1,
		PageSize: 10,
		CreateUser:UserNO
	
	}, function(data) {
		
		$("#hPageIndex").val("1");
		if (data.Items != null && data.Items.length > 0) {
			$("#all").html(""); ////全部清空
		for (var i = 0; i < data.Items.length; i++) {
		    var existingIndex = StockList.findIndex(item => item.BarcodeNO === data.Items[i].BarcodeNO);
		    
		    if (existingIndex === -1) {
		        var newItem = {};
		        var currentItem = data.Items[i];
		        
		        // Copy all properties from currentItem to newItem
		        for (var prop in currentItem) {
		            if (currentItem.hasOwnProperty(prop)) {
		                // Handle special property name cases
		                newItem[prop === 'Qty' ? 'StockQty' : prop] = currentItem[prop];
		            }
		        }
		        
		        StockList.push(newItem);
		    }
		}
			UpdateStockListDisplay();
		}
		else
		{
			mui.toast(data.Message, {
				duration: '1000',
				type: 'div'
			});
		}
	}, function(errr) {
		$("#all").html("");
		$("#all").html(
			'<a style="font-size:100px; color:#F27D48; display:block; text-align:center;" class="mui-icon mui-icon-search"></a><a class="mui-title" style="color:#808080; position: initial; margin: 0 auto; height:' +
			(window.screen.height - 480) + 'px">No data available at the moment</a>');
		StockList = [];
	})
}

//失败报警
function Audios() {
	var audio = new Audio('../../../fonts/baojin.mp3');

	audio.play();
}

function processChar(char) {
  // 尝试转换成数字
  const num = parseInt(char, 10);
  
  // 检查是否是有效数字（非 NaN 且原始字符完全匹配数字）
  if (!isNaN(num) && char.trim() === String(num)) {
    return num;  // 是数字，加 1
  } else {
    return 1;  // 不是数字，返回 1
  }
}
function PrevPage()
{
	var html = "";
	     var PageIndex=1;
	      var index=$("#hPageIndex").val();
		  if(index=="")
		  {
			PageIndex=1;
		  }
		  else
		  {
			PageIndex=  processChar(index)-1
			if(PageIndex<1)
			{
			  PageIndex=1;	
			}
			$("#hPageIndex").val(PageIndex);	
		  }
		xccFormPostAsync("api/PDA/TradePickBarcode", {
			TradeOrderNO: $("#TradeOrderNO").val(),
			PageIndex: PageIndex,
			PageSize: 10,
			CreateUser:UserNO
		
		}, function(data) {
			StockList=[];
			if (data.Items != null && data.Items.length > 0) {
				$("#all").html(""); ////全部清空
for (var i = 0; i < data.Items.length; i++) {
    var existingIndex = StockList.findIndex(item => item.BarcodeNO === data.Items[i].BarcodeNO);
    
    if (existingIndex === -1) {
        var newItem = {};
        var currentItem = data.Items[i];
        
        // Copy all properties from currentItem to newItem
        for (var prop in currentItem) {
            if (currentItem.hasOwnProperty(prop)) {
                // Handle special property name cases
                newItem[prop === 'Qty' ? 'StockQty' : prop] = currentItem[prop];
            }
        }
        
        StockList.push(newItem);
    }
}
				UpdateStockListDisplay();
			}
			else
			{
				mui.toast(data.Message, {
					duration: '1000',
					type: 'div'
				});
			}
		}, function(errr) {
			$("#all").html("");
			$("#all").html(
				'<a style="font-size:100px; color:#F27D48; display:block; text-align:center;" class="mui-icon mui-icon-search"></a><a class="mui-title" style="color:#808080; position: initial; margin: 0 auto; height:' +
				(window.screen.height - 480) + 'px">No data available at the moment</a>');
			StockList = [];
		})
	
}
function NextPage()
{
	var html = "";
	     var PageIndex=1;
	      var index=$("#hPageIndex").val();
		  if(index=="")
		  {
			PageIndex=1;
		  }
		  else
		  {
			PageIndex=  processChar(index)+1
			$("#hPageIndex").val(PageIndex);	
		  }
		xccFormPostAsync("api/PDA/TradePickBarcode", {
			TradeOrderNO: $("#TradeOrderNO").val(),
			PageIndex: PageIndex,
			PageSize: 10,
			CreateUser:UserNO
		
		}, function(data) {
			StockList=[];
			if (data.Items != null && data.Items.length > 0) {
				$("#all").html(""); ////全部清空
				for (var i = 0; i < data.Items.length; i++) {
				    var existingIndex = StockList.findIndex(item => item.BarcodeNO === data.Items[i].BarcodeNO);
				    
				    if (existingIndex === -1) {
				        var newItem = {};
				        var currentItem = data.Items[i];
				        
				        // Copy all properties from currentItem to newItem
				        for (var prop in currentItem) {
				            if (currentItem.hasOwnProperty(prop)) {
				                // Handle special property name cases
				                newItem[prop === 'Qty' ? 'StockQty' : prop] = currentItem[prop];
				            }
				        }
				        
				        StockList.push(newItem);
				    }
				}
				UpdateStockListDisplay();
			}
			else
			{
				mui.toast(data.Message, {
					duration: '1000',
					type: 'div'
				});
			}
		}, function(errr) {
			$("#all").html("");
			$("#all").html(
				'<a style="font-size:100px; color:#F27D48; display:block; text-align:center;" class="mui-icon mui-icon-search"></a><a class="mui-title" style="color:#808080; position: initial; margin: 0 auto; height:' +
				(window.screen.height - 480) + 'px">No data available at the moment</a>');
			StockList = [];
		})
	
}